package practise.alogrithm.hundredInterviewQuestions;

import practise.alogrithm.hundredInterviewQuestions.Utils.TreeBuilder;
import practise.alogrithm.hundredInterviewQuestions.Utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by richard on 6/2/14.
 */
public class PrintTreeNodesInWidth {
    TreeNode treeNode;
    Visitor visitor;

    public PrintTreeNodesInWidth(TreeNode treeNode) {
        this.treeNode = treeNode;

    }
    public void accept(Visitor visitor){
        this.visitor = visitor;
    }
    public void visitElement(TreeNode treeNode){
        if(treeNode!=null)
            visitor.visit(treeNode);
    }

    public void widthTree(){
        Queue<TreeNode> treeNodeQueue = new LinkedList<>();
        treeNodeQueue.offer(treeNode);
        while(!treeNodeQueue.isEmpty()){
            TreeNode treeNode1 = treeNodeQueue.poll();
            visitor.visit(treeNode1);
            if(treeNode1.getLeft()!=null)
                treeNodeQueue.offer(treeNode1.getLeft());
            if(treeNode1.getRight()!=null)
                treeNodeQueue.offer(treeNode1.getRight());
        }
    }
    public static void main(String[] args){
        TreeNode treeNode1 = TreeBuilder.createTreeByArrayInWidth(new int[]{8,6,10,5,7,9,11});
        PrintTreeNodesInWidth printTreeNodesInWidth = new PrintTreeNodesInWidth(treeNode1);
        printTreeNodesInWidth.accept(new Visitor());
        printTreeNodesInWidth.widthTree();
    }
}

class Visitor{
    public void visit(TreeNode treeNode){
        System.out.print(treeNode.getValue()+" ");
    }
}
